package com.sgb.kjwl.view.ui.fragment.packers;

import androidx.databinding.DataBindingUtil;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;

import com.sgb.kjwl.AppFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentProjectTeamBinding;
import com.sgb.kjwl.di.packers.DaggerPackersFragmentComponent;
import com.sgb.kjwl.di.packers.PackersFragmentModule;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.kjwl.model.entity.request.PackersProjectTeamListEntity;
import com.sgb.kjwl.view.event.ProjectTeamEvent;
import com.sgb.kjwl.view.ui.activity.WebViewX5HostActivity;
import com.sgb.kjwl.view.ui.adapter.packers.PackersProjectTeamListAdapter;
import com.sgb.kjwl.view.widget.ProjectTeamPopWindow;
import com.sgb.kjwl.viewmodel.packers.ProjectTeamFragmentModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.xrecyclerview.XRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

public class PackersProjectTeamFragment extends AppFragment {

    private FragmentProjectTeamBinding binding;
    private PackersProjectTeamListAdapter pickingAdapter;
    private ProjectTeamPopWindow statusPopWindow;
    private ProjectTeamPopWindow scalPopWindow;
    private ProjectTeamPopWindow teamPopWindow;
    private ProjectTeamPopWindow typePopWindow;

    @Inject
    ProjectTeamFragmentModel model;

    private List<PickSelectEntity> typeDatas = new ArrayList<>();
    private List<PickSelectEntity> scalDatas = new ArrayList<>();
    private List<PickSelectEntity> statusDatas = new ArrayList<>();
    private List<PickSelectEntity> teamDatas = new ArrayList<>();

    private String typeNo = "";
    private String scalNo = "";
    private String scalName="";
    private String teamNo = "";
    private String statusNo = "";
    private int page = 1;

    private boolean isLoadMore = false;
    public static String KEY_TYPE_Id = "typeId";
    public static String KEY_POSITION = "position";
    public static String KEY_Cid = "cid";
    private String secondId = "";
    private String firstId = "";
    private int position;
    private ProjectTeamEvent event;

    public static PackersProjectTeamFragment newInstance(String cid,String typeId, int position) {
        PackersProjectTeamFragment fragment = new PackersProjectTeamFragment();
        Bundle bundle = new Bundle();
        bundle.putString(KEY_Cid, cid);
        bundle.putString(KEY_TYPE_Id, typeId);
        bundle.putInt(KEY_POSITION, position);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerPackersFragmentComponent
                .builder()
                .appComponent(appComponent)
                .packersFragmentModule(new PackersFragmentModule(this))
                .build()
                .inject(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_project_team, container, false);
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        firstId = getArguments().getString(KEY_Cid);
        secondId = getArguments().getString(KEY_TYPE_Id);
        position = getArguments().getInt(KEY_POSITION);

        initView();
        initData();
    }

    private void initView() {

        event = new ProjectTeamEvent();
        event.setCidNo("000");
        event.setTypeNo("");
        event.setScalNo("");
        event.setTeamNo("");
        event.setStatusNo("");

        binding.statusLayout.setOnClickListener(this);
        binding.teamLayout.setOnClickListener(this);
        binding.scalLayout.setOnClickListener(this);
        binding.typeLayout.setOnClickListener(this);

        typePopWindow = new ProjectTeamPopWindow(getActivity());
        typePopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object type, Object key2, Object key3) {
//                LogUtil.v("goodsInfo","类型="+((PickSelectEntity)type).getProjectscale());
                typeNo = ((PickSelectEntity)type).getNo();
                binding.tvType.setText(((PickSelectEntity)type).getProjectscale());

             binding.tvType.setTextColor(getResources().getColor(R.color.color_main));
               binding.typeLayoutRoot.setBackgroundResource(R.drawable.bg_pick_hall_selected);
               binding.typeArrowView.setImageResource(R.mipmap.icon_down_red);

                typePopWindow.setType(typeNo);
                event.setTypeNo(typeNo);
                EventBus.getDefault().postSticky(event);
                getData();
            }
        });
        typePopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                String type=binding.tvType.getText().toString();
                if(type.equals("工程专项")){
                    binding.typeArrowView.setImageResource(R.mipmap.pick_select_down_normal);
                    binding.tvType.setTextColor(getResources().getColor(R.color.color_tab_one));
                }else {
                    binding.typeArrowView.setImageResource(R.mipmap.icon_down_red);
                }
            }
        });

        scalPopWindow = new ProjectTeamPopWindow(getActivity());
        scalPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object type, Object key2, Object key3) {
//                LogUtil.v("goodsInfo","规模="+((PickSelectEntity)type).getProjectscale());
                scalNo = ((PickSelectEntity)type).getNo();
                if(((PickSelectEntity)type).getProjectscale().equals("全部")) {
                    scalName ="";
                }else{
                    scalName = ((PickSelectEntity) type).getProjectscale();
                }
                binding.tvScal.setText(((PickSelectEntity)type).getProjectscale());
                binding.tvScal.setTextColor(getResources().getColor(R.color.color_main));
                binding.scalArrowView.setImageResource(R.mipmap.icon_down_red);
                binding.scalLayoutRoot.setBackgroundResource(R.drawable.bg_pick_hall_selected);
                scalPopWindow.setType(scalNo);
                event.setScalNo(scalNo);
                EventBus.getDefault().postSticky(event);
                getData();
            }
        });
        scalPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                String scal=binding.tvScal.getText().toString();
                if(scal.equals("团队规模")){
                    binding.scalArrowView.setImageResource(R.mipmap.pick_select_down_normal);
                    binding.tvScal.setTextColor(getResources().getColor(R.color.color_tab_one));
                }else {
                    binding.scalArrowView.setImageResource(R.mipmap.icon_down_red);
                }
            }
        });

        teamPopWindow = new ProjectTeamPopWindow(getActivity());
        teamPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object type, Object key2, Object key3) {
//                LogUtil.v("goodsInfo","团队="+((PickSelectEntity)type).getProjectscale());
                teamNo = ((PickSelectEntity)type).getNo();
                binding.tvTeam.setText(((PickSelectEntity)type).getProjectscale());
//                binding.tvAddr.setTextColor(getResources().getColor(R.color.new_blue));
//                binding.addrLayoutRoot.setBackgroundResource(R.drawable.bg_pick_hall_selected);
//                binding.sortArrowView.setImageResource(R.mipmap.pick_select_down);
                binding.tvTeam.setTextColor(getResources().getColor(R.color.color_main));
                binding.teamLayoutRoot.setBackgroundResource(R.drawable.bg_pick_hall_selected);
                binding.teamArrowView.setImageResource(R.mipmap.icon_down_red);
                teamPopWindow.setType(teamNo);
                event.setTeamNo(teamNo);
                EventBus.getDefault().postSticky(event);
                getData();
            }
        });
        teamPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                String team=binding.tvTeam.getText().toString();
                if(team.equals("团队类型")){
                    binding.teamArrowView.setImageResource(R.mipmap.pick_select_down_normal);
                    binding.tvTeam.setTextColor(getResources().getColor(R.color.color_333333));
                }else {
                    binding.teamArrowView.setImageResource(R.mipmap.icon_down_red);
                }
            }
        });

        statusPopWindow = new ProjectTeamPopWindow(getActivity());
        statusPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object type, Object key2, Object key3) {
                if(null!=type){
//                    LogUtil.v("goodsInfo","状态="+((PickSelectEntity)type).getProjectscale());
                    statusNo = ((PickSelectEntity)type).getNo();
                    binding.tvStatus.setText(((PickSelectEntity)type).getProjectscale());
//               binding.tvStatus.setTextColor(getResources().getColor(R.color.new_blue));
//              binding.statusLayoutRoot.setBackgroundResource(R.drawable.bg_pick_hall_selected);
//               binding.typeArrowView.setImageResource(R.mipmap.pick_select_down);
//
//                }else{
//                    statusNo = "";
//                    binding.tvStatus.setText("招标状态");
                }
                statusPopWindow.setType(statusNo);
                event.setStatusNo(statusNo);
                EventBus.getDefault().postSticky(event);

                getData();
            }
        });

        if (pickingAdapter == null) {
            pickingAdapter = new PackersProjectTeamListAdapter(getActivity(), null);
        }
        DividerItemDecoration divider = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.shape_list_divide));
        binding.recyclerView.addItemDecoration(divider);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        binding.recyclerView.setLayoutManager(layoutManager);
        binding.recyclerView.setAdapter(pickingAdapter);
        binding.recyclerView.setLoadingMoreEnabled(true);
        binding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                getData();
            }

            @Override
            public void onLoadMore() {
                isLoadMore = true;
                page = page+1;
                model.getList(firstId,secondId,typeNo,teamNo, scalName,statusNo,page);
            }
        });

        pickingAdapter.setOnItemClick(new AdapterOnItemClick<PackersProjectTeamListEntity>() {
            @Override
            public void onItemClick(PackersProjectTeamListEntity tenderListEntity, int position) {
                model.getH5Url(tenderListEntity.getNo());
            }
        });
    }

    private void initData() {
        model.getFilterTypeData(secondId);
        model.getScaleData();
        setStatusDatas();
        setTeamDatas();

        getData();
    }

    private void getData(){
        isLoadMore = false;
        page = 1;
        model.getList(firstId,secondId,typeNo,teamNo, scalName,statusNo,page);
    }

    public void showUrl(String url) {
        WebViewX5HostActivity.start(getActivity(), url);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);

        switch (v.getId()){
            case R.id.status_layout:
                if (null != statusDatas && statusDatas.size() > 0) {
                    statusPopWindow.showPopwindow(binding.roomLayout, 0, 0);
                    statusPopWindow.setData(statusDatas);
                }
                break;
            case R.id.scal_layout:
                binding.tvScal.setTextColor(getResources().getColor(R.color.new_blue));
                binding.scalArrowView.setImageResource(R.mipmap.pick_select_up_normal);
                if (null != scalDatas && scalDatas.size() > 0) {
                    scalPopWindow.showPopwindow(binding.roomLayout, 0, 0);
                    scalPopWindow.setData(scalDatas);
                }
                break;
            case R.id.team_layout:
                binding.tvTeam.setTextColor(getResources().getColor(R.color.new_blue));
                binding.teamArrowView.setImageResource(R.mipmap.pick_select_up_normal);
                if (null != teamDatas && teamDatas.size() > 0) {
                    teamPopWindow.showPopwindow(binding.roomLayout, 0, 0);
                    teamPopWindow.setData(teamDatas);
                }
                break;
            case R.id.type_layout:
                if (null != typeDatas && typeDatas.size() > 0) {
                    binding.tvType.setTextColor(getResources().getColor(R.color.new_blue));
                    binding.typeArrowView.setImageResource(R.mipmap.pick_select_up_normal);
                    typePopWindow.showPopwindow(binding.roomLayout, 0, 0);
                    typePopWindow.setData(typeDatas);
                }
                break;
        }
    }

    public void showList(List<PackersProjectTeamListEntity> list) {
        binding.recyclerView.refreshComplete();
        if (isLoadMore) {
            binding.recyclerView.loadMoreComplete();
            if (list.size() > 0) {
                pickingAdapter.addDatas(list);
            } else {
                binding.recyclerView.setLoadingMoreEnabled(false);
            }
            binding.recyclerView.setVisibility(View.VISIBLE);
        } else {
            binding.recyclerView.refreshComplete();
            if (null!=list && list.size() > 0) {
                binding.recyclerView.setVisibility(View.VISIBLE);
                binding.emptyView.setVisibility(View.GONE);
                pickingAdapter.setDatas(list);
                binding.recyclerView.setLoadingMoreEnabled(true);
            } else {
                pickingAdapter.setDatas(null);
                binding.recyclerView.setVisibility(View.GONE);
                binding.emptyView.setVisibility(View.VISIBLE);
            }
        }
    }

    public void setTypeDatas(List<PickSelectEntity> datas) {
        typeDatas.clear();
        PickSelectEntity entity = new PickSelectEntity();
        entity.setNo("0");
        entity.setProjectscale("全部");
        typeDatas.add(0,entity);
        typeDatas.addAll(datas);
    }

    public void setStatusDatas() {
        statusDatas.clear();
        PickSelectEntity entity = new PickSelectEntity();
        entity.setNo("-1");
        entity.setProjectscale("全部");
        PickSelectEntity entity1 = new PickSelectEntity();
        entity1.setNo("1");
        entity1.setProjectscale("可出工");
        PickSelectEntity entity2 = new PickSelectEntity();
        entity2.setNo("0");
        entity2.setProjectscale("不可出工");
        statusDatas.add(entity);
        statusDatas.add(entity1);
        statusDatas.add(entity2);
    }

    public void setScalDatas(List<PickSelectEntity> datas) {
        scalDatas.clear();
        PickSelectEntity entity = new PickSelectEntity();
        entity.setNo("0");
        entity.setProjectscale("全部");
        scalDatas.add(0,entity);
        scalDatas.addAll(datas);
    }

    public void setTeamDatas() {
        teamDatas.clear();
        PickSelectEntity entity = new PickSelectEntity();
        entity.setNo("-1");
        entity.setProjectscale("全部");
        PickSelectEntity entity1 = new PickSelectEntity();
        entity1.setNo("0");
        entity1.setProjectscale("个人");
        PickSelectEntity entity2 = new PickSelectEntity();
        entity2.setNo("1");
        entity2.setProjectscale("企业");
        teamDatas.add(entity);
        teamDatas.add(entity1);
        teamDatas.add(entity2);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(ProjectTeamEvent event) {
        if (event.getCidNo().equals(secondId)) {
            isLoadMore = false;
            page = 1;

            typeNo = event.getTypeNo();
            teamNo = event.getTeamNo();
            scalNo = event.getScalNo();
            statusNo = event.getStatusNo();
            scalName=event.getScalName();

            if(null!=typePopWindow){
                typePopWindow.setType(typeNo);
                if(TextUtils.isEmpty(typeNo)){
                    binding.tvType.setText("业务类型");
                    binding.teamArrowView.setImageResource(R.mipmap.pick_select_down_normal);
                    binding.tvType.setTextColor(getResources().getColor(R.color.color_333333));
                    binding.typeLayoutRoot.setBackgroundResource(R.drawable.corner999_f5f5f5_bg);
                }
                if(null!=typeDatas){
                    for(int i=0;i<typeDatas.size();i++){
                        if(typeNo.equals(typeDatas.get(i).getNo())){
                            binding.tvType.setText(typeDatas.get(i).getProjectscale());
                            binding.tvType.setTextColor(getResources().getColor(R.color.new_blue));
                            binding.typeLayoutRoot.setBackgroundResource(R.drawable.bg_pick_hall_selected);
                            binding.typeArrowView.setImageResource(R.mipmap.icon_down_red);
                        }
                    }
                }
            }
            if(null!=scalPopWindow){
                scalPopWindow.setType(scalNo);
                if(TextUtils.isEmpty(scalNo)){
                    binding.tvScal.setText("团队规模");
                    binding.scalArrowView.setImageResource(R.mipmap.pick_select_down_normal);
                    binding.tvScal.setTextColor(getResources().getColor(R.color.color_333333));
                    binding.scalLayoutRoot.setBackgroundResource(R.drawable.corner999_f5f5f5_bg);
                }
                if(null!=scalDatas){
                    for(int i=0;i<scalDatas.size();i++){
                        if(scalNo.equals(scalDatas.get(i).getNo())){
                            binding.tvScal.setText(scalDatas.get(i).getProjectscale());
                            binding.tvScal.setTextColor(getResources().getColor(R.color.new_blue));
                            binding.scalLayoutRoot.setBackgroundResource(R.drawable.bg_pick_hall_selected);
                            binding.scalArrowView.setImageResource(R.mipmap.icon_down_red);
                        }
                    }
                }
            }
            if(null!=teamPopWindow){
                teamPopWindow.setType(teamNo);
                if(TextUtils.isEmpty(teamNo)){
                    binding.tvTeam.setText("团队类型");
                    binding.teamArrowView.setImageResource(R.mipmap.pick_select_down_normal);
                    binding.tvTeam.setTextColor(getResources().getColor(R.color.color_333333));
                    binding.teamLayoutRoot.setBackgroundResource(R.drawable.corner999_f5f5f5_bg);
                }
                if(null!=teamDatas){
                    for(int i=0;i<teamDatas.size();i++){
                        if(teamNo.equals(teamDatas.get(i).getNo())){
                            binding.tvTeam.setText(teamDatas.get(i).getProjectscale());
                            binding.tvTeam.setTextColor(getResources().getColor(R.color.new_blue));
                            binding.teamLayoutRoot.setBackgroundResource(R.drawable.bg_pick_hall_selected);
                            binding.teamArrowView.setImageResource(R.mipmap.icon_down_red);
                        }
                    }
                }
            }
            if(null!=statusPopWindow){
                statusPopWindow.setType(statusNo);
                if(TextUtils.isEmpty(statusNo)){
                    binding.tvStatus.setText("团队状态");
                }
                if(null!=statusDatas){
                    for(int i=0;i<statusDatas.size();i++){
                        if(statusNo.equals(statusDatas.get(i).getNo())){
                            binding.tvStatus.setText(statusDatas.get(i).getProjectscale());
                        }
                    }
                }
            }

            model.getList(firstId,event.getCidNo(),event.getTypeNo(),event.getTeamNo(), event.getScalName(),event.getStatusNo(),page);
        }
        EventBus.getDefault().removeStickyEvent(event);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if(getUserVisibleHint() && isVisibleToUser){
            if(null!=event){
                if(null!=binding && null!=binding.roomLayout){
                    binding.roomLayout.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            event.setTypeNo(typeNo);
                            event.setScalNo(scalNo);
                            event.setTeamNo(teamNo);
                            event.setStatusNo(statusNo);
                            EventBus.getDefault().postSticky(event);
                        }
                    },500);
                }
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
